//
//  MGSplitViewController.m
//  MGSplitView
//
//  Created by Matt Gemmell on 26/07/2010.
//  Copyright 2010 Instinctive Code.
//

#import "MGSplitViewController.h"
#import "MGSplitDividerView.h"
#import "MGSplitCornersView.h"
#import "MGChartViewController.h"
#import "MGTreeViewController.h"

#define MG_DEFAULT_SPLIT_POSITION		320.0	// default width of master view in UISplitViewController.
#define MG_DEFAULT_SPLIT_POSITION_MASTER		320.0	// default width of master view in UISplitViewController.
#define MG_DEFAULT_SPLIT_WIDTH			1.0		// default width of split-gutter in UISplitViewController.
#define MG_DEFAULT_CORNER_RADIUS		5.0		// default corner-radius of overlapping split-inner corners on the master and detail views.
#define MG_DEFAULT_CORNER_COLOR			[UIColor blackColor]	// default color of intruding inner corners (and divider background).

#define MG_PANESPLITTER_CORNER_RADIUS	0.0		// corner-radius of split-inner corners for MGSplitViewDividerStylePaneSplitter style.
#define MG_PANESPLITTER_SPLIT_WIDTH		25.0	// width of split-gutter for MGSplitViewDividerStylePaneSplitter style.

#define MG_MIN_VIEW_WIDTH				200.0	// minimum width a view is allowed to become as a result of changing the splitPosition.

#define MG_ANIMATION_CHANGE_SPLIT_ORIENTATION	@"ChangeSplitOrientation"	// Animation ID for internal use.
#define MG_ANIMATION_CHANGE_SUBVIEWS_ORDER		@"ChangeSubviewsOrder"	// Animation ID for internal use.


@interface MGSplitViewController (MGPrivateMethods)

 
- (CGSize)splitViewSizeForOrientation:(UIInterfaceOrientation)theOrientation;
- (void)layoutSubviews;
- (void)layoutSubviewsWithAnimation:(BOOL)animate;
- (void)layoutSubviewsForInterfaceOrientation:(UIInterfaceOrientation)theOrientation withAnimation:(BOOL)animate;
- (BOOL)is_shouldShow_TreeAndQuote_ForInterfaceOrientation:(UIInterfaceOrientation)theOrientation;
- (BOOL)is_shouldShow_TreeAndQuote;
- (NSString *)nameOfInterfaceOrientation:(UIInterfaceOrientation)theOrientation;
//- (void)reconfigureForMasterInPopover:(BOOL)inPopover;

@end


@implementation MGSplitViewController
@synthesize chartViewController;

#pragma mark -
#pragma mark Orientation helpers


- (NSString *)nameOfInterfaceOrientation:(UIInterfaceOrientation)theOrientation
{
	NSString *orientationName = nil;
	switch (theOrientation) {
		case UIInterfaceOrientationPortrait:
			orientationName = @"Portrait"; // Home button at bottom
			break;
		case UIInterfaceOrientationPortraitUpsideDown:
			orientationName = @"Portrait (Upside Down)"; // Home button at top
			break;
		case UIInterfaceOrientationLandscapeLeft:
			orientationName = @"Landscape (Left)"; // Home button on left
			break;
		case UIInterfaceOrientationLandscapeRight:
			orientationName = @"Landscape (Right)"; // Home button on right
			break;
		default:
			break;
	}
	
	return orientationName;
}


- (BOOL)isLandscape
{
	return UIInterfaceOrientationIsLandscape(self.interfaceOrientation);
}


- (BOOL)is_shouldShow_TreeAndQuote_ForInterfaceOrientation:(UIInterfaceOrientation)theOrientation
{
	// Returns YES if master view should be shown directly embedded in the splitview, instead of hidden in a popover.
	return ((UIInterfaceOrientationIsLandscape(theOrientation)) ? _showsMasterInLandscape : _showsMasterInPortrait);
}


- (BOOL)is_shouldShow_TreeAndQuote
{
	return [self is_shouldShow_TreeAndQuote_ForInterfaceOrientation:self.interfaceOrientation];
}


- (BOOL)isShowingMaster
{
	return [self is_shouldShow_TreeAndQuote] && self.treeViewController && self.treeViewController.view && ([self.treeViewController.view superview] == self.view);
}


#pragma mark -
#pragma mark 初始化 與消滅
 
- (id)init
{
	if ((self = [super init])) {
		
        NSLog(@"init MGSplitViewController");         
        
                 
        _viewControllers = [[NSMutableArray alloc] initWithObjects:[NSNull null], [NSNull null], [NSNull null], nil];
        
        //設定屬性初始值
        _showsMasterInPortrait = YES;
        _showsMasterInLandscape = YES;
        _reconfigurePopup = NO;
        _vertical = NO;
        _masterBeforeDetail = YES;
        
        _splitPosition = MG_DEFAULT_SPLIT_POSITION; //分割區起點
        _splitPosition_master = MG_DEFAULT_SPLIT_POSITION_MASTER; //分割區起點 
        
        _splitWidth = MG_DEFAULT_SPLIT_WIDTH;       //分割畫面條狀設定
        
        {
            CGRect divRect = self.view.bounds;
            if ([self isVertical]) {
               
                divRect.origin.y = _splitPosition;
                divRect.size.height = _splitWidth;
            } else {
               
                divRect.origin.x = _splitPosition;
                divRect.size.width = _splitWidth;
            }
            
            _dividerView_chart = [[MGSplitDividerView alloc] initWithFrame:divRect];
            [_dividerView_chart setIsdivide_master:NO]; 
            
            
            _dividerView_chart.splitViewController = self;
            _dividerView_chart.backgroundColor = MG_DEFAULT_CORNER_COLOR;
            _dividerStyle = MGSplitViewDividerStyleThin;
            
            CGRect divRect_master = self.view.bounds;
            
            if ([self isVertical]) {
                divRect_master.origin.x = _splitPosition_master;
                divRect_master.origin.y = 0;
                divRect_master.size.width = _splitWidth;
                divRect_master.size.height = _splitPosition;
                
            } else {
                divRect_master.origin.x = _splitPosition;
                divRect_master.size.width = _splitWidth;
            }        
            
            
            _dividerView_tree_quote = [[MGSplitDividerView alloc] initWithFrame:divRect_master]; 
            
            [_dividerView_tree_quote setIsdivide_master:YES];
            
            _dividerView_tree_quote.splitViewController = self;
            _dividerView_tree_quote.backgroundColor = MG_DEFAULT_CORNER_COLOR;
            
            
        }
	}
	
	return self;
}
  
- (void)dealloc
{
	_delegate = nil;
	[self.view.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
	[_viewControllers release];
	[_barButtonItem release];
	 
	
    [_dividerView_chart release];
    [_dividerView_tree_quote release];    
	
    [_cornerViews release];
	
	[super dealloc];
}

#pragma mark -
#pragma mark 設定取出 次視窗控制器

//設定
- (void)setViewControllers:(NSArray *)controllers
{
	NSLog(@"setViewControllers 取得次視窗控制器後 開始排列畫面");
    
    if (controllers != _viewControllers) {
       
        //1.移除之前的 _viewControllers (基本動作)
        for (UIViewController *controller in _viewControllers) {
			if ([controller isKindOfClass:[UIViewController class]]) {
				[controller.view removeFromSuperview];
			}
		}
		[_viewControllers release];
		
        //2.設定新的 _viewControllers
        _viewControllers = [[NSMutableArray alloc] initWithCapacity:2];
		
        if (controllers && [controllers count] >= 2) {
		    //重點 設定次controller
            NSLog(@"self.treeViewController");
            self.treeViewController  = [controllers objectAtIndex:0];
			 NSLog(@"self.chartViewController");            
            self.chartViewController = [controllers objectAtIndex:1];
		     NSLog(@"self.quoteViewController");            
            self.quoteViewController = [controllers objectAtIndex:2]; 
            
        } else {
			NSLog(@"設定次視窗錯誤 %@ requires 2 view-controllers. (%@)", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
		}
        
		//3.開始排列
		[self layoutSubviews];
	}
}

//取出
- (NSArray *)viewControllers
{
	return [[_viewControllers copy] autorelease];
}

#pragma mark -
#pragma mark 設定 ViewController

- (void)setChartViewController:(UIViewController *)detail{
	
    NSLog(@"setDetailViewController");
   
    if (!_viewControllers) {
		_viewControllers = [[NSMutableArray alloc] initWithCapacity:3];
		[_viewControllers addObject:[NSNull null]];
	}
	
	BOOL changed = YES;
	if ([_viewControllers count] > 1) {
		if ([_viewControllers objectAtIndex:1] == detail) {
			changed = NO;
		} else {
			[_viewControllers replaceObjectAtIndex:1 withObject:detail];
		}
		
	} else {
		[_viewControllers addObject:detail];
	}
	
	if (changed) {
		[self layoutSubviews];
	}
}
- (void)setQuoteViewController:(UIViewController *)quoteViewController{
	NSLog(@"setQuoteViewController");
    
    if (!_viewControllers) {
		_viewControllers = [[NSMutableArray alloc] initWithCapacity:3];
	}
	
    
	NSObject *newMaster = quoteViewController;
	if (!newMaster) {
		newMaster = [NSNull null];
	}
	
	BOOL changed = YES;
    
    if ([_viewControllers count] > 2) {
		if ([_viewControllers objectAtIndex:2] == newMaster) {
			changed = NO;
		} else {
			[_viewControllers replaceObjectAtIndex:2 withObject:newMaster];
		}
		
	} else {
		[_viewControllers addObject:newMaster];
	}
    
    
	if (changed) {
		[self layoutSubviews];
	}
}
- (void)setTreeViewController:(UIViewController *)master{
	NSLog(@"setTreeViewController");
    if (!_viewControllers) {
		_viewControllers = [[NSMutableArray alloc] initWithCapacity:3];
	}
	
	NSObject *newMaster = master;
	if (!newMaster) {
		newMaster = [NSNull null];
	}
	
	BOOL changed = YES;
    
	if ([_viewControllers count] > 0) {
		if ([_viewControllers objectAtIndex:0] == newMaster) {
			changed = NO;
		} else {
			[_viewControllers replaceObjectAtIndex:0 withObject:newMaster];
		}
		
	} else {
		[_viewControllers addObject:newMaster];
	}
	
	if (changed) {
		[self layoutSubviews];
	}
}

#pragma mark -
#pragma mark 取出 ViewController

-(UIViewController *)quoteViewController{
    if (_viewControllers && [_viewControllers count] > 2) {
		NSObject *controller = [_viewControllers objectAtIndex:2];
		if ([controller isKindOfClass:[UIViewController class]]) {
			return [[(UIViewController *)controller retain] autorelease];
		}
	}
	
	return nil;
}
-(UIViewController *)chartViewController{
	if (_viewControllers && [_viewControllers count] > 1) {
		NSObject *controller = [_viewControllers objectAtIndex:1];
		if ([controller isKindOfClass:[UIViewController class]]) {
			return [[(UIViewController *)controller retain] autorelease];
		}
	}
	
	return nil;
}
-(UIViewController *)treeViewController{
	if (_viewControllers && [_viewControllers count] > 0) {
		NSObject *controller = [_viewControllers objectAtIndex:0];
		if ([controller isKindOfClass:[UIViewController class]]) {
			return [[(UIViewController *)controller retain] autorelease];
		}
	}
	
	return nil;
}


#pragma mark -
#pragma mark 排列次視窗控制器畫面
//排版0
- (void)layoutSubviews
{
	NSLog(@"排列次視窗控制器畫面.0 layoutSubviews");
    [self layoutSubviewsForInterfaceOrientation:self.interfaceOrientation withAnimation:YES];
    
      
}

//排版1
- (void)layoutSubviewsForInterfaceOrientation:(UIInterfaceOrientation)theOrientation withAnimation:(BOOL)animate
{
	NSLog(@"排列次視窗控制器畫面.1 layoutSubviewsForInterfaceOrientation"); 
	
	// Layout the master, detail and divider views appropriately, adding/removing subviews as needed.
	// First obtain relevant geometry.
	
    //取出該狀態下的全部螢幕高度與寬度
    CGSize fullSize = [self splitViewSizeForOrientation:theOrientation];
	float width = fullSize.width;
	float height = fullSize.height;
	
	if (YES) { // Just for debugging.
		NSLog(@"Target orientation is %@, dimensions will be %.0f x %.0f", 
			  [self nameOfInterfaceOrientation:theOrientation], width, height);
	}
	
	// Layout the master, divider and detail views.
	CGRect newFrame = CGRectMake(0, 0, width, height);
	
    UIViewController *controller;
	UIView *theView;
	
    BOOL shouldShow_TreeAndQuote = [self is_shouldShow_TreeAndQuote_ForInterfaceOrientation:theOrientation];
	BOOL masterFirst = [self isMasterBeforeDetail];
	     
    //調整各區塊與分隔線大小
    {
         
        CGRect treeRect, chartRect, dividerRect_chart,dividerRect_tree_quote,quoteRect;        
        if ([self isVertical]) {
            //垂直狀態 Master on left, detail on right (or vice versa).
            NSLog(@"垂直分隔 Master on left, detail on right (or vice versa).");
           
            if (masterFirst) {
                //表格在前面
                NSLog(@"表格在前面");
                
                //框架數據調整
                {
                    //0.是否顯示樹狀與報價
                    {
                        if (!shouldShow_TreeAndQuote) {
                            // Move off-screen.
                            newFrame.origin.x -= (_splitPosition + _splitWidth);
                        }          
                    }
                    
                    //1.樹狀
                    {
                        treeRect.size.width=_splitPosition;
                        treeRect.size.height=_splitPosition_master;
                        treeRect.origin.x= newFrame.origin.x;
                        treeRect.origin.y= newFrame.origin.y;                    
                    }
                    
                    //2.樹狀與報價表中間的分割線
                    {
                        dividerRect_tree_quote.size.width =  _splitPosition;
                        dividerRect_tree_quote.size.height= _splitWidth;
                        dividerRect_tree_quote.origin.x   = newFrame.origin.x  ;
                        dividerRect_tree_quote.origin.y   = newFrame.origin.y + _splitPosition_master;  
                        
                    }                
                    
                    //3.報價表
                    {
                        quoteRect.size.width = _splitPosition;
                        quoteRect.size.height= height-( _splitPosition_master + _splitWidth);
                        quoteRect.origin.x=newFrame.origin.x ;
                        quoteRect.origin.y=newFrame.origin.y + _splitPosition_master+_splitWidth;                    
                    }
                    
                    //4.走勢圖與（樹狀與報價）分割線
                    {
                        dividerRect_chart.size.width=_splitWidth  ;
                        dividerRect_chart.size.height=height;
                        dividerRect_chart.origin.x=newFrame.origin.x + _splitPosition;
                        dividerRect_chart.origin.y=newFrame.origin.y  ;                        
                    }                   
                    
                    //5.走勢圖
                    {
                        chartRect.size.height=height ;
                        
                        if (!shouldShow_TreeAndQuote) {                    
                            chartRect.size.width=width  ;
                        }
                        else {
                            chartRect.size.width=width - ( _splitPosition+_splitWidth);
                            
                        }
                        
                        chartRect.origin.x=newFrame.origin.x + _splitPosition+_splitWidth ;
                        chartRect.origin.y=newFrame.origin.y ;                      
                    }
                    
                }            
                
                
            } 
            else {
                //表格在後面
                NSLog(@"表格在後面");
                
                //框架數據調整
                {
                    //0.是否顯示樹狀與報價
                    if (!shouldShow_TreeAndQuote) {
                        // Move off-screen.
                        newFrame.size.width += (_splitPosition + _splitWidth);
                    }
                    
                    
                    //1.走勢圖
                    {
                        chartRect.size.width=width - ( _splitPosition+_splitWidth)  ;
                        chartRect.size.height=height ;
                        chartRect.origin.x=newFrame.origin.x;
                        chartRect.origin.y=newFrame.origin.y;                      
                    }  
                    
                    //2.走勢圖與（樹狀與報價）分割線
                    {
                        dividerRect_chart.size.width=_splitWidth ;
                        dividerRect_chart.size.height=height;
                        dividerRect_chart.origin.x=newFrame.origin.x + width - ( _splitPosition+_splitWidth) ;
                        dividerRect_chart.origin.y=newFrame.origin.y ;                        
                    }  
                    
                    //3.樹狀
                    {
                        treeRect.size.width= _splitPosition;
                        treeRect.size.height=_splitPosition_master ;
                        treeRect.origin.x= newFrame.origin.x + width - ( _splitPosition+_splitWidth) +_splitWidth;
                        treeRect.origin.y= newFrame.origin.y ;                    
                    }
                    
                    //4.樹狀與報價表中間的分割線
                    {
                        dividerRect_tree_quote.size.width=  _splitPosition;
                        dividerRect_tree_quote.size.height= _splitWidth ;
                        dividerRect_tree_quote.origin.x= newFrame.origin.x + width - ( _splitPosition+_splitWidth) +_splitWidth;
                        dividerRect_tree_quote.origin.y= newFrame.origin.y+ _splitPosition_master ;  
                        
                    } 
                    
                    //5.報價表
                    {
                        quoteRect.size.width=_splitPosition ;
                        quoteRect.size.height=height -(_splitPosition_master+_splitWidth);
                        
                        quoteRect.origin.x=newFrame.origin.x + width - ( _splitPosition+_splitWidth) +_splitWidth;
                        quoteRect.origin.y= newFrame.origin.y + _splitPosition_master+_splitWidth;  
                        
                    }    
                    
                }                 
                
            }
                        
            
            
        } 
        else{
            NSLog(@"水平分割 修改的是y 值位置與高度");
            // Master above, detail below (or vice versa).
                        
            if (masterFirst) {
                
                NSLog(@"報價表在前面");
                
                
                
                //框架數據調整
                {
                    //0.是否顯示樹狀與報價
                    {
                        if (!shouldShow_TreeAndQuote) {
                            //NSLog(@"沒有顯示tableview origin.y=%f _splitPosition=%f _splitWidth=%f", newFrame.origin.y, _splitPosition,_splitWidth );                
                            
                            //如果隱藏樹狀與報價表 將整個坐標軸往上移動 _splitPosition + _splitWidth
                            newFrame.origin.y -= (_splitPosition + _splitWidth);
                            
                            //NSLog(@"新 沒有顯示tableview origin.y=%f _splitPosition=%f _splitWidth=%f", newFrame.origin.y, _splitPosition,_splitWidth );                
                        }                
                    }
                    
                    //1.樹狀
                    {
                        treeRect.size.width=_splitPosition_master;
                        treeRect.size.height=_splitPosition;
                        treeRect.origin.x= newFrame.origin.x;
                        treeRect.origin.y= newFrame.origin.y;                    
                    }
                    
                    //2.樹狀與報價表中間的分割線
                    {
                        dividerRect_tree_quote.size.width=  _splitWidth;
                        dividerRect_tree_quote.size.height= _splitPosition ;
                        dividerRect_tree_quote.origin.x= newFrame.origin.x + _splitPosition_master;
                        dividerRect_tree_quote.origin.y= newFrame.origin.y;  
                        
                    }                
                    
                    //3.報價表
                    {
                        
                        quoteRect.size.width=width -_splitPosition_master-_splitWidth;
                       
                        /*下面這段程式原本是應該為
                         quoteRect.size.height=_splitPosition ;
                        主要是因為有一個bug 一開始表格高度會縮減 所以才改成兩倍高度
                         
                         */
                        quoteRect.size.height=_splitPosition+_splitPosition ;
                        
                        
                        quoteRect.origin.x=newFrame.origin.x + _splitPosition_master+_splitWidth;
                        quoteRect.origin.y=newFrame.origin.y;                    
                    }
                    
                    //4.走勢圖與（樹狀與報價）分割線
                    {
                        dividerRect_chart.size.width=width  ;
                        dividerRect_chart.size.height=_splitWidth;
                        dividerRect_chart.origin.x=newFrame.origin.x  ;
                        dividerRect_chart.origin.y=newFrame.origin.y + _splitPosition;                        
                    }                   
                    
                    //5.走勢圖
                    {
                        chartRect.size.width=width  ;
                        if (!shouldShow_TreeAndQuote) {                    
                            chartRect.size.height=height  ;
                        }
                        else {
                            chartRect.size.height=height - ( _splitPosition+_splitWidth);
                            
                        }
                        
                        chartRect.origin.x=newFrame.origin.x  ;
                        chartRect.origin.y=newFrame.origin.y + _splitPosition+_splitWidth;                      
                    }            
                }
                
                
            } 
            else {
                NSLog(@"報價表在後面");            
                
                //框架數據調整
                {
                    //0.是否顯示樹狀與報價
                    if (!shouldShow_TreeAndQuote) {
                        //不顯示樹狀與報價
                        newFrame.size.height += (_splitPosition + _splitWidth);
                    }                
                    
                    //1.走勢圖
                    {
                        chartRect.size.width=width  ;
                        chartRect.size.height=height - ( _splitPosition+_splitWidth);
                        chartRect.origin.x=newFrame.origin.x;
                        chartRect.origin.y=newFrame.origin.y;                      
                    }            
                    //2.走勢圖與（樹狀與報價）分割線
                    {
                                                 
                        dividerRect_chart.size.width=width  ;
                        dividerRect_chart.size.height=_splitWidth;
                        dividerRect_chart.origin.x=newFrame.origin.x  ;
                        dividerRect_chart.origin.y=newFrame.origin.y + height - ( _splitPosition+_splitWidth);                        
                    }                 
                    //3.樹狀
                    {
                        treeRect.size.width= _splitPosition_master;
                        treeRect.size.height=_splitPosition;
                        treeRect.origin.x= newFrame.origin.x;
                        treeRect.origin.y= newFrame.origin.y + height - ( _splitPosition+_splitWidth) +_splitWidth;                    
                    }
                    //4.樹狀與報價表中間的分割線
                    {
                        dividerRect_tree_quote.size.width=  _splitWidth;
                        dividerRect_tree_quote.size.height= _splitPosition;
                        dividerRect_tree_quote.origin.x= newFrame.origin.x + _splitPosition_master;
                        dividerRect_tree_quote.origin.y= newFrame.origin.y + height - ( _splitPosition+_splitWidth) +_splitWidth;  
                        
                    }                   
                    //5.報價表
                    {
                        quoteRect.size.width=width -_splitPosition_master-_splitWidth;
                        quoteRect.size.height=_splitPosition;
                        quoteRect.origin.x=newFrame.origin.x + _splitPosition_master+_splitWidth;
                        quoteRect.origin.y= newFrame.origin.y + height - ( _splitPosition+_splitWidth) +_splitWidth;  
                        
                    }                   
                }            
                
            }
            
            
            
        }
        
        //視窗控制器
        {
            //treeViewController
            controller = self.treeViewController;
            if (controller && [controller isKindOfClass:[UIViewController class]])  {
                
                theView = controller.view;    //第一次執行viewDidLoad，如果之前已經有，就不在執行
               
                if (theView) {
                   
                    theView.frame = treeRect;  //重新設定框架
                    [(MGTreeViewController *)controller view_frame_size_change:treeRect];  //通知樹狀controller框架大小改變
                    
                    
                    if (!theView.superview) {  //沒有上層view
                       
                        [controller viewWillAppear:NO];
                                               
                        [self.view addSubview:theView];
                                                
                        [controller viewDidAppear:NO];
                    }
                }
                
            }
            
            //quoteViewController
            
            controller = self.quoteViewController;
            
            if (controller && [controller isKindOfClass:[UIViewController class]])  {
                theView = controller.view;
                if (theView) {
                    theView.frame = quoteRect;//執行 viewDidLoad
                    if (!theView.superview) {
                        [controller viewWillAppear:NO];
                        [self.view addSubview:theView];
                        [controller viewDidAppear:NO];
                    }
                }
            }           
            
            //chartViewController
            controller = self.chartViewController;
            if (controller && [controller isKindOfClass:[UIViewController class]])  {
                theView = controller.view;
                if (theView) {
                    
                    theView.frame = chartRect;//執行 viewDidLoad
                    //重要：此段程式是用來呼叫重設走勢圖框架
                    [(MGChartViewController *)controller set_new_frame:chartRect];
                    
                    if (!theView.superview) {
                        [self.view insertSubview:theView aboveSubview:self.treeViewController.view];
                    } else {
                        [self.view bringSubviewToFront:theView];
                    }
                    
                }
            }            
        }
        
        //分隔線
        {
            
            //_dividerView_chart
            theView = _dividerView_chart;
            theView.frame = dividerRect_chart;
            if (!theView.superview) {
                [self.view addSubview:theView];
            }
            
            //_dividerView_tree_quote
            theView = _dividerView_tree_quote;
            theView.frame = dividerRect_tree_quote;
            if (!theView.superview) {
                [self.view addSubview:theView];
            }      
        }            
    }
    
	//產生小圓角 美觀使用.
    {
        MGSplitCornersView *leadingCorners; // top/left of screen in vertical/horizontal split.
        MGSplitCornersView *trailingCorners; // bottom/right of screen in vertical/horizontal split.
        
        if (!_cornerViews) {
            CGRect cornerRect = CGRectMake(0, 0, 10, 10); // arbitrary, will be resized below.
            leadingCorners = [[MGSplitCornersView alloc] initWithFrame:cornerRect];
            leadingCorners.splitViewController = self;
            leadingCorners.cornerBackgroundColor = MG_DEFAULT_CORNER_COLOR;
            leadingCorners.cornerRadius = MG_DEFAULT_CORNER_RADIUS;
            
            trailingCorners = [[MGSplitCornersView alloc] initWithFrame:cornerRect];
            trailingCorners.splitViewController = self;
            trailingCorners.cornerBackgroundColor = MG_DEFAULT_CORNER_COLOR;
            trailingCorners.cornerRadius = MG_DEFAULT_CORNER_RADIUS;
            
            _cornerViews = [[NSArray alloc] initWithObjects:leadingCorners, trailingCorners, nil];
            
            [leadingCorners release];
            [trailingCorners release];
            
        } else if ([_cornerViews count] == 2) {
            
            leadingCorners = [_cornerViews objectAtIndex:0];
            trailingCorners = [_cornerViews objectAtIndex:1];
        }
        
        // Configure and layout the corner-views.
        
        
        leadingCorners.cornersPosition = (_vertical) ? MGCornersPositionLeadingVertical : MGCornersPositionLeadingHorizontal;
        trailingCorners.cornersPosition = (_vertical) ? MGCornersPositionTrailingVertical : MGCornersPositionTrailingHorizontal;
        
        leadingCorners.autoresizingMask = (_vertical) ? UIViewAutoresizingFlexibleBottomMargin : UIViewAutoresizingFlexibleRightMargin;
        trailingCorners.autoresizingMask = (_vertical) ? UIViewAutoresizingFlexibleTopMargin : UIViewAutoresizingFlexibleLeftMargin;
        
        float x, y, cornersWidth, cornersHeight;
        
        CGRect leadingRect, trailingRect;
        
        float radius = leadingCorners.cornerRadius;
        
        if (_vertical) { // left/right split
            cornersWidth = (radius * 2.0) + _splitWidth;
            cornersHeight = radius;
            x = ((shouldShow_TreeAndQuote) ? ((masterFirst) ? _splitPosition : width - (_splitPosition + _splitWidth)) : (0 - _splitWidth)) - radius;
            y = 0;
            
            leadingRect = CGRectMake(x, y, cornersWidth, cornersHeight); // top corners
            trailingRect = CGRectMake(x, (height - cornersHeight), cornersWidth, cornersHeight); // bottom corners
            
        } else { // top/bottom split
            x = 0;
            y = ((shouldShow_TreeAndQuote) ? ((masterFirst) ? _splitPosition : height - (_splitPosition + _splitWidth)) : (0 - _splitWidth)) - radius;
            cornersWidth = radius;
            cornersHeight = (radius * 2.0) + _splitWidth;
            leadingRect = CGRectMake(x, y, cornersWidth, cornersHeight); // left corners
            trailingRect = CGRectMake((width - cornersWidth), y, cornersWidth, cornersHeight); // right corners
        }
        
        leadingCorners.frame = leadingRect;
        trailingCorners.frame = trailingRect;
        
        //Ensure corners are visible and frontmost.
        if (!leadingCorners.superview) {
            [self.view insertSubview:leadingCorners aboveSubview:self.chartViewController.view];
            [self.view insertSubview:trailingCorners aboveSubview:self.chartViewController.view];
        }
        else {
            [self.view bringSubviewToFront:leadingCorners];
            [self.view bringSubviewToFront:trailingCorners];
        } 
        
    }
    
}

#pragma mark -
#pragma mark View management


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}






- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
	[self.treeViewController willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
	[self.chartViewController willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
}


- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
	[self.treeViewController didRotateFromInterfaceOrientation:fromInterfaceOrientation];
	[self.chartViewController didRotateFromInterfaceOrientation:fromInterfaceOrientation];
}


- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation 
										 duration:(NSTimeInterval)duration
{
	[self.treeViewController willAnimateRotationToInterfaceOrientation:toInterfaceOrientation duration:duration];
	[self.chartViewController willAnimateRotationToInterfaceOrientation:toInterfaceOrientation duration:duration];
	
	 
	
	// Re-tile views.
	_reconfigurePopup = YES;
	[self layoutSubviewsForInterfaceOrientation:toInterfaceOrientation withAnimation:YES];
}


- (void)willAnimateFirstHalfOfRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
	[self.treeViewController willAnimateFirstHalfOfRotationToInterfaceOrientation:toInterfaceOrientation duration:duration];
	[self.chartViewController willAnimateFirstHalfOfRotationToInterfaceOrientation:toInterfaceOrientation duration:duration];
}


- (void)didAnimateFirstHalfOfRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
	[self.treeViewController didAnimateFirstHalfOfRotationToInterfaceOrientation:toInterfaceOrientation];
	[self.chartViewController didAnimateFirstHalfOfRotationToInterfaceOrientation:toInterfaceOrientation];
}


- (void)willAnimateSecondHalfOfRotationFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation duration:(NSTimeInterval)duration
{
	[self.treeViewController willAnimateSecondHalfOfRotationFromInterfaceOrientation:fromInterfaceOrientation duration:duration];
	[self.chartViewController willAnimateSecondHalfOfRotationFromInterfaceOrientation:fromInterfaceOrientation duration:duration];
}


- (CGSize)splitViewSizeForOrientation:(UIInterfaceOrientation)theOrientation
{
	UIScreen *screen = [UIScreen mainScreen];
	CGRect fullScreenRect = screen.bounds; // always implicitly in Portrait orientation.
	CGRect appFrame = screen.applicationFrame;
	
	// Find status bar height by checking which dimension of the applicationFrame is narrower than screen bounds.
	// Little bit ugly looking, but it'll still work even if they change the status bar height in future.
	float statusBarHeight = MAX((fullScreenRect.size.width - appFrame.size.width), (fullScreenRect.size.height - appFrame.size.height));
	
	// Initially assume portrait orientation.
	float width = fullScreenRect.size.width;
	float height = fullScreenRect.size.height;
	
	// Correct for orientation.
	if (UIInterfaceOrientationIsLandscape(theOrientation)) {
		width = height;
		height = fullScreenRect.size.width;
	}
	
	// Account for status bar, which always subtracts from the height (since it's always at the top of the screen).
	height -= statusBarHeight;
	
	return CGSizeMake(width, height);
}




- (void)layoutSubviewsWithAnimation:(BOOL)animate
{
	NSLog(@"layoutSubviewsWithAnimation");
    [self layoutSubviewsForInterfaceOrientation:self.interfaceOrientation withAnimation:animate];
}

#pragma mark -view-Appear 視窗顯示事件
#pragma mark


- (void)viewWillAppear:(BOOL)animated
{
	NSLog(@"viewWillAppear MGSplitViewController");
    [super viewWillAppear:animated];
	
	if ([self isShowingMaster]) {
		[self.treeViewController viewWillAppear:animated];
	}
	[self.chartViewController viewWillAppear:animated];
	
	_reconfigurePopup = YES;
	[self layoutSubviews];
}


- (void)viewDidAppear:(BOOL)animated
{
	NSLog(@"viewDidAppear MGSplitViewController");
    
    [super viewDidAppear:animated];
	
    NSLog(@"次視窗完成顯示，判斷是否要顯示哪些次視窗");
	 
    //次視窗完成顯示，判斷是否要顯示哪些次視窗 此段程式無作用 因為之前已經先執行過顯示
    {
        if ([self isShowingMaster]) {
            [self.treeViewController viewDidAppear:animated];
            [self.quoteViewController viewDidAppear:animated];
        }
        [self.chartViewController viewDidAppear:animated];
    }
        
}


- (void)viewWillDisappear:(BOOL)animated
{
	NSLog(@"viewWillDisappear");
    [super viewWillDisappear:animated];
	
	if ([self isShowingMaster]) {
		[self.treeViewController viewWillDisappear:animated];
	}
	[self.chartViewController viewWillDisappear:animated];
}


- (void)viewDidDisappear:(BOOL)animated
{
	NSLog(@"viewDidDisappear");
    
    [super viewDidDisappear:animated];
	
	if ([self isShowingMaster]) {
		[self.treeViewController viewDidDisappear:animated];
	}
	[self.chartViewController viewDidDisappear:animated];
}

 
#pragma mark -
#pragma mark 動畫


- (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
{
	if (([animationID isEqualToString:MG_ANIMATION_CHANGE_SPLIT_ORIENTATION] || 
		 [animationID isEqualToString:MG_ANIMATION_CHANGE_SUBVIEWS_ORDER])
		&& _cornerViews) {
		for (UIView *corner in _cornerViews) {
			corner.hidden = NO;
		}
		_dividerView_chart.hidden = NO;
	}
}


#pragma mark -
#pragma mark 動作


-(void)toggleSplitOrientation:(id)sender
{
	BOOL showingMaster = [self isShowingMaster];
	if (showingMaster) {
		if (_cornerViews) {
			for (UIView *corner in _cornerViews) {
				corner.hidden = YES;
			}
			_dividerView_chart.hidden = YES;
		}
		[UIView beginAnimations:MG_ANIMATION_CHANGE_SPLIT_ORIENTATION context:nil];
		[UIView setAnimationDelegate:self];
		[UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];
	}
	self.vertical = (!self.vertical);
	if (showingMaster) {
		[UIView commitAnimations];
	}
    
}
 
- (void)toggleMasterBeforeDetail:(id)sender
{
	BOOL showingMaster = [self isShowingMaster];
	if (showingMaster) {
		if (_cornerViews) {
			for (UIView *corner in _cornerViews) {
				corner.hidden = YES;
			}
			_dividerView_chart.hidden = YES;
		}
		[UIView beginAnimations:MG_ANIMATION_CHANGE_SUBVIEWS_ORDER context:nil];
		[UIView setAnimationDelegate:self];
		[UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];
	}
	self.masterBeforeDetail = (!self.masterBeforeDetail);
	if (showingMaster) {
		[UIView commitAnimations];
	}
    
}
 
- (void)toggleMasterView:(id)sender
{
	NSLog(@"toggleMasterView");
    
	
	if (![self isShowingMaster]) {
		// We're about to show the master view. Ensure it's in place off-screen to be animated in.
		_reconfigurePopup = YES;
		//[self reconfigureForMasterInPopover:NO];
		[self layoutSubviews];
	}
	
	// This action functions on the current primary orientation; it is independent of the other primary orientation.
	[UIView beginAnimations:@"toggleMaster" context:nil];
	if (self.isLandscape) {
		self.showsMasterInLandscape = !_showsMasterInLandscape;
	} else {
		self.showsMasterInPortrait = !_showsMasterInPortrait;
	}
	[UIView commitAnimations];
    
}
 
#pragma mark -
#pragma mark Accessors and properties


- (id)delegate
{
	return _delegate;
}


- (void)setDelegate:(id <MGSplitViewControllerDelegate>)newDelegate
{
	if (newDelegate != _delegate && 
		(!newDelegate || [(NSObject *)newDelegate conformsToProtocol:@protocol(MGSplitViewControllerDelegate)])) {
		_delegate = newDelegate;
	}
}


- (BOOL)showsMasterInPortrait
{
	return _showsMasterInPortrait;
}


- (void)setShowsMasterInPortrait:(BOOL)flag
{
	NSLog(@"setShowsMasterInPortrait");
    if (flag != _showsMasterInPortrait) {
		_showsMasterInPortrait = flag;
		
		if (![self isLandscape]) { // i.e. if this will cause a visual change.
			 
			
			// Rearrange views.
			_reconfigurePopup = YES;
			[self layoutSubviews];
		}
	}
}


- (BOOL)showsMasterInLandscape
{
	return _showsMasterInLandscape;
}


- (void)setShowsMasterInLandscape:(BOOL)flag
{
	NSLog(@"setShowsMasterInLandscape");
    if (flag != _showsMasterInLandscape) {
		_showsMasterInLandscape = flag;
		
		if ([self isLandscape]) { // i.e. if this will cause a visual change.
			 
			
			// Rearrange views.
			_reconfigurePopup = YES;
			[self layoutSubviews];
		}
	}
}


- (BOOL)isVertical
{
	return _vertical;
}


- (void)setVertical:(BOOL)flag
{
	NSLog(@"setVertical");
    if (flag != _vertical) {
		 
		
		_vertical = flag;
		
		// Inform delegate.
		if (_delegate && [_delegate respondsToSelector:@selector(splitViewController:willChangeSplitOrientationToVertical:)]) {
			[_delegate splitViewController:self willChangeSplitOrientationToVertical:_vertical];
		}
		
		[self layoutSubviews];
	}
}


- (BOOL)isMasterBeforeDetail
{
	return _masterBeforeDetail;
}


- (void)setMasterBeforeDetail:(BOOL)flag
{
	NSLog(@"setMasterBeforeDetail");
    if (flag != _masterBeforeDetail) {
		 
		
		_masterBeforeDetail = flag;
		
		if ([self isShowingMaster]) {
			[self layoutSubviews];
		}
	}
}

#pragma mark -
#pragma mark 執行分割動作

- (float)splitPositionaa:(BOOL)isdividemaster{

    if (isdividemaster) {
        NSLog(@"_splitPosition_master");
        return _splitPosition_master;
    }
    else {
        NSLog(@"splitPosition");
        return _splitPosition;
    }
}
- (void)setsplitPositionaa:(float)splitposition isdividemaster:(BOOL)isdividemaster{
    
    if (isdividemaster) {
        // Check to see if delegate wishes to constrain the position.
        NSLog(@"fffgghhhh");       
        // Check to see if delegate wishes to constrain the position.
        float newPosn = splitposition;
        BOOL constrained = NO;
        
        //此時螢幕的大小
        CGSize fullSize = [self splitViewSizeForOrientation:self.interfaceOrientation];
        NSLog(@"fullSize width=%f height=%f",fullSize.width,fullSize.height);
        
        
        if (_delegate && [_delegate respondsToSelector:@selector(splitViewController:constrainSplitPosition:splitViewSize:)]) {
            
            newPosn = [_delegate splitViewController:self constrainSplitPosition:newPosn splitViewSize:fullSize];
            constrained = YES; //相信會有反應 implicitly trust delegate's response.
            
        } else {
            // Apply default constraints if delegate doesn't wish to participate.
            float minPos = MG_MIN_VIEW_WIDTH;
            float maxPos = ((_vertical) ? fullSize.width : fullSize.height) - (MG_MIN_VIEW_WIDTH + _splitWidth);
            constrained = (newPosn != _splitPosition_master && newPosn >= minPos && newPosn <= maxPos);
        }
        
        
        if (constrained) {
            
            
            _splitPosition_master = newPosn;
            
            // Inform delegate.
            if (_delegate && [_delegate respondsToSelector:@selector(splitViewController:willMoveSplitToPosition:)]) {
                //通知移動到新位置
                [_delegate splitViewController:self willMoveSplitToPosition:_splitPosition_master];
                
            }
            
            if ([self isShowingMaster]) {
                //重新排版
                NSLog(@"重新排版 新位置=%f",_splitPosition);
                [self layoutSubviews];
            }
        }        
        
        
    }
    else {
        NSLog(@"setSplitPosition posn");
        
        // Check to see if delegate wishes to constrain the position.
        float newPosn = splitposition;
        BOOL constrained = NO;
        
        //此時螢幕的大小
        CGSize fullSize = [self splitViewSizeForOrientation:self.interfaceOrientation];
        NSLog(@"fullSize width=%f height=%f",fullSize.width,fullSize.height);
        
        
        if (_delegate && [_delegate respondsToSelector:@selector(splitViewController:constrainSplitPosition:splitViewSize:)]) {
            
            newPosn = [_delegate splitViewController:self constrainSplitPosition:newPosn splitViewSize:fullSize];
            constrained = YES; //相信會有反應 implicitly trust delegate's response.
            
        } else {
            // Apply default constraints if delegate doesn't wish to participate.
            float minPos = MG_MIN_VIEW_WIDTH;
            float maxPos = ((_vertical) ? fullSize.width : fullSize.height) - (MG_MIN_VIEW_WIDTH + _splitWidth);
            constrained = (newPosn != _splitPosition && newPosn >= minPos && newPosn <= maxPos);
        }
        
        
        if (constrained) {
            
            
            _splitPosition = newPosn;
            
            // Inform delegate.
            if (_delegate && [_delegate respondsToSelector:@selector(splitViewController:willMoveSplitToPosition:)]) {
                //通知移動到新位置
                [_delegate splitViewController:self willMoveSplitToPosition:_splitPosition];
                
            }
            
            if ([self isShowingMaster]) {
                //重新排版
                NSLog(@"重新排版 新位置=%f",_splitPosition);
                [self layoutSubviews];
            }
        }

    }
    
    
}
/*
- (float)splitPosition
{
	NSLog(@"splitPosition");
    return _splitPosition;
}


- (void)setSplitPosition:(float)posn
{
	NSLog(@"setSplitPosition posn");
    
    // Check to see if delegate wishes to constrain the position.
	float newPosn = posn;
	BOOL constrained = NO;
    
    //此時螢幕的大小
	CGSize fullSize = [self splitViewSizeForOrientation:self.interfaceOrientation];
	NSLog(@"fullSize width=%f height=%f",fullSize.width,fullSize.height);
    
    
    if (_delegate && [_delegate respondsToSelector:@selector(splitViewController:constrainSplitPosition:splitViewSize:)]) {
        
		newPosn = [_delegate splitViewController:self constrainSplitPosition:newPosn splitViewSize:fullSize];
		constrained = YES; //相信會有反應 implicitly trust delegate's response.
		
	} else {
		// Apply default constraints if delegate doesn't wish to participate.
		float minPos = MG_MIN_VIEW_WIDTH;
		float maxPos = ((_vertical) ? fullSize.width : fullSize.height) - (MG_MIN_VIEW_WIDTH + _splitWidth);
		constrained = (newPosn != _splitPosition && newPosn >= minPos && newPosn <= maxPos);
	}
	
	
    if (constrained) {
		
        
		_splitPosition = newPosn;
		
		// Inform delegate.
		if (_delegate && [_delegate respondsToSelector:@selector(splitViewController:willMoveSplitToPosition:)]) {
	        //通知移動到新位置
            [_delegate splitViewController:self willMoveSplitToPosition:_splitPosition];
            
		}
		
		if ([self isShowingMaster]) {
            //重新排版
            NSLog(@"重新排版 新位置=%f",_splitPosition);
			[self layoutSubviews];
		}
	}
}
*/


- (void)setSplitPosition:(float)posn animated:(BOOL)animate
{
	NSLog(@"setSplitPosition posn animated");
  
    BOOL shouldAnimate = (animate && [self isShowingMaster]);
	if (shouldAnimate) {
		[UIView beginAnimations:@"SplitPosition" context:nil];
	}
	[self setsplitPositionaa:posn isdividemaster:YES];
	if (shouldAnimate) {
		[UIView commitAnimations];
	}
}


- (float)splitWidth
{
	return _splitWidth;
}


- (void)setSplitWidth:(float)width
{
	NSLog(@"setSplitWidth");
    if (width != _splitWidth && width >= 0) {
		_splitWidth = width;
		if ([self isShowingMaster]) {
			[self layoutSubviews];
		}
	}
}





- (MGSplitDividerView *)dividerView
{
	return [[_dividerView_chart retain] autorelease];
}


- (void)setDividerView:(MGSplitDividerView *)divider
{
	NSLog(@"setDividerView");
    if (divider != _dividerView_chart) {
		[_dividerView_chart removeFromSuperview];
		[_dividerView_chart release];
		_dividerView_chart = [divider retain];
		_dividerView_chart.splitViewController = self;
		_dividerView_chart.backgroundColor = MG_DEFAULT_CORNER_COLOR;
		if ([self isShowingMaster]) {
			[self layoutSubviews];
		}
	}
}


- (BOOL)allowsDraggingDivider
{
	if (_dividerView_chart) {
		return _dividerView_chart.allowsDragging;
	}
	
	return NO;
}


- (void)setAllowsDraggingDivider:(BOOL)flag
{
	NSLog(@"setAllowsDraggingDivider");
    if (self.allowsDraggingDivider != flag && _dividerView_chart) {
		
        _dividerView_chart.allowsDragging = flag;
        _dividerView_tree_quote.allowsDragging = flag;        
         
        
	}
    

}


- (MGSplitViewDividerStyle)dividerStyle
{
	return _dividerStyle;
}


- (void)setDividerStyle:(MGSplitViewDividerStyle)newStyle
{
	NSLog(@"setDividerStyle");
    
     
	
	// We don't check to see if newStyle equals _dividerStyle, because it's a meta-setting.
	// Aspects could have been changed since it was set.
	_dividerStyle = newStyle;
	
	// Reconfigure general appearance and behaviour.
	float cornerRadius;
    cornerRadius=0;
	if (_dividerStyle == MGSplitViewDividerStyleThin) {
		cornerRadius = MG_DEFAULT_CORNER_RADIUS;
		_splitWidth = MG_DEFAULT_SPLIT_WIDTH;
		self.allowsDraggingDivider = NO;
		
	} else if (_dividerStyle == MGSplitViewDividerStylePaneSplitter) {
		cornerRadius = MG_PANESPLITTER_CORNER_RADIUS;
		_splitWidth = MG_PANESPLITTER_SPLIT_WIDTH;
		self.allowsDraggingDivider = YES;
	}
	
	// Update divider and corners.
	[_dividerView_chart setNeedsDisplay];

	if (_cornerViews) {
		for (MGSplitCornersView *corner in _cornerViews) {
			corner.cornerRadius = cornerRadius;
		}
	}
	
	// Layout all views.
	[self layoutSubviews];
}


- (void)setDividerStyle:(MGSplitViewDividerStyle)newStyle animated:(BOOL)animate
{
	BOOL shouldAnimate = (animate && [self isShowingMaster]);
	if (shouldAnimate) {
		[UIView beginAnimations:@"DividerStyle" context:nil];
	}
	[self setDividerStyle:newStyle];
	if (shouldAnimate) {
		[UIView commitAnimations];
	}
}


- (NSArray *)cornerViews
{
	if (_cornerViews) {
		return [[_cornerViews retain] autorelease];
	}
	
	return nil;
}



#pragma mark -
#pragma mark 記憶體管理

- (void)didReceiveMemoryWarning
{
    NSLog(@"記憶體警告********");
    
     
    [super didReceiveMemoryWarning];
    
    
}
@end
